<template>
	<view class="user-info">
		<!-- 头部信息，包含头像和name -->
		<view class="content">
			<head-image :name="userInfo.name" :url="userInfo.headImage" :size="160"
				@click="onShowFullImage()"></head-image>
			<view class="info-item">
				<text>{{userInfo.name}}</text>
			</view>
		</view>
		<view class="line"></view>
		<!-- 修改后的提示信息 -->
		<view v-if="isDataChanged" class="data-changed-tip">数据已修改，记得点击保存修改按钮哦！</view>

		<view class="tabContent" v-show="true">
			<view class="paramBox">
				<view class="param-title">个人信息</view>
				<view class="param-item">
					<label>性别</label>
					<uni-data-select v-model="userInfo.gender" :localdata="genderOption" @change="handleGenderChange"
						:clear="false" class="text">
					</uni-data-select>
				</view>
				<view class="param-item">
					<label>生日</label>
					<picker mode="date" v-model="userInfo.birthday" @change="handleDateChange" class="picker">
						<text class="text">{{userInfo.birthday}}</text>
					</picker>
				</view>
				<view class="param-item">
					<label>籍贯</label>
					<view class="picker2">
						<uni-data-picker :placeholder="userInfo.city" popup-title="请选择城市" collection="opendb-city-china"
							field="code as value, name as text" orderby="value asc" :step-searh="true" self-field="code"
							parent-field="parent_code" @change="handleCityChange" :maxLevel="2">
						</uni-data-picker>
					</view>
				</view>
				<view v-if="userInfo.relative!= ''">
					<view v-for="(relative, relativeIndex) in userInfo.relative" :key="relativeIndex">
						<view class="param-item">
							<label>联系人{{relativeIndex + 1}}</label>
							<uni-easyinput prefixIcon="person" :inputBorder='false' v-model="relative.name"
								:placeholderStyle="placeholderStyle" :placeholder=relative.name
								@input="handleRelativeNameChange($event, relativeIndex)">
							</uni-easyinput>
						</view>
						<view class="param-item">
							<label>手机号码{{relativeIndex + 1}}</label>
							<uni-easyinput prefixIcon="phone" :inputBorder='false' v-model="relative.phone"
								:placeholderStyle="placeholderStyle" :placeholder=relative.phone
								@input="handleRelativePhoneChange($event, relativeIndex)">
							</uni-easyinput>
						</view>
					</view>
				</view>
				<view class=" param-title">学校信息
				</view>
				<view class="param-item">
					<label>年级</label>
					<button @click="openGradeTermPopup" class='button' plain="true">
						{{ userInfo.grade }}</button>
				</view>
				<vk-data-goods-sku-popup ref="skuPopup" v-model="gradeTermPopupData.show" border-radius="20"
					:z-index="990" :localdata="gradeGoodsInfo" :selected-init="true" :default-select="defaultSku"
					:mode="gradeTermPopupData.mode" :theme="gradeTermPopupData.theme"
					:show-close="gradeTermPopupData.showClose" :hide-stock="gradeTermPopupData.hideStock"
					:mask-close-able="gradeTermPopupData.maskCloseAble" @open="onOpenGradeTermPopup"
					@close="onCloseGradeTermPopup" @add-cart="confirmGradeTermSelection"></vk-data-goods-sku-popup>
				<view class="param-item">
					<label>班级</label>
					<uni-easyinput prefixIcon="heart" :inputBorder='false' v-model='userInfo.class'
						:placeholderStyle="placeholderStyle">
					</uni-easyinput>
				</view>
				<view class="param-item">
					<label>备注</label>
					<uni-easyinput prefixIcon="edit" :inputBorder='false' v-model="userInfo.notes"
						:placeholderStyle="placeholderStyle">
					</uni-easyinput>
				</view>
			</view>
			<!-- 隔离与按钮直接的间隔 -->
			<view style="height: 30rpx;"></view>
			<!-- 按钮部分 -->
			<view class="button-group">
				<view>
					<button class="my-button" type="primary" @tap="savaInfo">保存修改</button>
				</view>
				<view>
					<button class="my-button" type="warn" @tap="delInfo">删除信息</button>
				</view>
			</view>

			<!-- 按钮部分 -->
			<view class="button-group">
				<view>
					<button class="my-button" style="background-color: #00ff00;"
						@click="redirectScoreInput">成绩录入</button>
				</view>
				<view>
					<button class="my-button" style="background-color: greenyellow;"
						@tap="redirectScoreInfo">成绩信息</button>
				</view>
			</view>
			<!-- 按钮部分 -->
			<view class="button-group">
				<view>
					<button class="my-button" style="background-color: #ffaa00;" @tap="savaInfo">课程录入</button>
				</view>
				<view>
					<button class="my-button" style="background-color: #ffaa7f;" @tap="delInfo">课程信息</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		reactive,
		onMounted,
		watch,
		toRefs,
		onUpdated,
		nextTick
	} from 'vue';
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app';
	import vkDataGoodsSkuPopup from '@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup.vue';
	import {
		gender_options,
		default_stage_grade
	} from '@/utils/enum.js';
	import {
		city_list
	} from '@/utils/city_list.js';

	import _ from 'lodash'; // 引入lodash库，用于深拷贝等操作，在UPDATE_STUDENT等mutation中有用到

	export default {
		components: {
			vkDataGoodsSkuPopup
		},
		setup() {
			const url_input = "/pages/score/score-input?id="
			const url_info = "/pages/score/score-info?id="
			const db_student = uniCloud.importObject("db_student");
			const genderOption = gender_options;
			const cityList = city_list;
			const placeholderStyle = "color:#000000;font-size:14px;font-weight:546;";
			const gradeList = default_stage_grade;

			// 使用reactive创建响应式数据对象userInfo
			const state = reactive({
				userInfo: {},
				originUserInfo: {},
				gradeGoodsInfo: {},
				gradeTermPopupData: {
					show: false,
					goods_id: "001",
					theme: "default",
					showClose: true,
					maskCloseAble: false,
				},
				defaultSku: {
					sku: []
				},
				isDataChanged: false
			});


			// 处理选择性别变化，仅更新组件内userInfo的gender数据，暂不立即调用studentStore更新
			const handleGenderChange = (e) => {
				state.userInfo.gender = e;
			};

			// 处理选择生日日期变化，仅更新组件内userInfo的birthday数据，暂不立即调用studentStore更新
			const handleDateChange = (e) => {
				state.userInfo.birthday = e.detail.value;
			};

			// 处理选择籍贯城市变化，仅更新组件内userInfo的ancestral_home数据，暂不立即调用studentStore更新
			const handleCityChange = (e) => {
				state.userInfo.city = e.detail.value;
			};

			const handleRelativeNameChange = (e, index) => {
				// 使用更新后的联系人对象替换原数组中的对应联系人，仅更新组件内数据，暂不立即调用studentStore更新
				state.userInfo.relative[index].name = e;
			};

			const handleRelativePhoneChange = (e, index) => {
				// 使用更新后的联系人对象对应的手机号码替换原数组中的原手机号码，仅更新组件内数据，暂不立即调用studentStore更新
				state.userInfo.relative[index].phone = e;
			};

			// 打开年级学期选择弹窗
			const openGradeTermPopup = () => {
				state.gradeGoodsInfo = getGradeTermGoodsInfo(state.gradeTermPopupData.goods_id);
				if (!state.gradeGoodsInfo) {
					console.error('未获取到有效的年级学期商品信息');
					return;
				}
				state.gradeTermPopupData.show = true;
			};

			// 获取年级学期商品信息
			const getGradeTermGoodsInfo = (goodsId) => {
				return gradeList.find((item) => item._id === goodsId) || null;
			};

			// 年级学期选择弹窗打开时的监听方法
			const onOpenGradeTermPopup = () => {
				console.log("监听 - 打开年级学期选择组件");
			};

			// 年级学期选择弹窗关闭时的监听方法
			const onCloseGradeTermPopup = () => {
				console.log("监听 - 关闭年级学期选择组件");
			};

			// 年级学期选择确认后的逻辑处理，仅更新组件内userInfo的相关年级、学期等信息，暂不立即调用studentStore更新
			const confirmGradeTermSelection = async (selectShop) => {
				console.log("监听 - 年级学期确认选择", selectShop);
				if (selectShop) {
					state.userInfo.grade = selectShop.goods_name
				}
				setTimeout(() => {
					state.gradeTermPopupData.show = false;
				}, 300);
			};

			const savaInfo = (async () => {
				// 保存修改的逻辑，调用updateStudent action来保存修改后的信息
				try {
					await db_student.updateStudent(state.userInfo);
					uni.showToast({
						title: '学生信息更新成功',
						icon: 'success'
					});
				} catch (error) {
					uni.showToast({
						title: '学生信息更新失败，请重试',
						icon: 'none'
					});
					console.error('更新学生信息出错:', error);
				}
				state.originUserInfo = _.cloneDeep(state.userInfo);
				state.isDataChanged = false;
			});

			const delInfo = (async () => {
				// 删除信息的逻辑，调用studentStore的removeStudent action来删除（根据学生id删除）
				try {
					await db_student.removeStudentById(state.userInfo._id);
					uni.showToast({
						title: '学生信息删除成功',
						icon: 'success'
					});
				} catch (error) {
					uni.showToast({
						title: '学生信息删除失败',
						icon: 'none'
					});
					console.error('删除学生信息出错:', error);
				}
				state.isDataChanged = false;
			});
			const redirectScoreInput = () => {
				// 跳转到score-input页面
				uni.navigateTo({
					url: url_input + state.userInfo._id
				});
			};

			const redirectScoreInfo = () => {
				// 跳转到score-input页面
				uni.navigateTo({
					url: url_info + state.userInfo._id
				});
			};

			onMounted(() => {});

			// 在页面加载流程
			onLoad(async (options) => {
				console.log('进入onLoad生命周期钩子，准备加载用户信息，获取到的id值为：', options.id);
				// 调用云对象的getStudentInfo方法获取某一个学生的数据，这是一个异步操作
				const studentData = await db_student.getStudentById(options.id);
				if (studentData) {
					state.userInfo = studentData;
					//数据深拷贝，确保 originUserInfo 是一份独立的数据副本
					state.originUserInfo = _.cloneDeep(studentData);
					// 页面加载时，直接加载赋值gradeGoodsInfo，方便赋值defaultSku
					state.gradeGoodsInfo = getGradeTermGoodsInfo(state.gradeTermPopupData.goods_id);
					state.defaultSku.sku = state.gradeGoodsInfo['sku_list'].find((sku) => sku.goods_name ===
						state.userInfo.grade).sku_name_arr
				} else {
					console.error(`未找到id为${options.id}的学生信息`);
				}
				console.log('完成loadUserInfo调用');
				console.log('onLoad state.userInfo', state.userInfo)
			});

			watch(() => state.userInfo, () => {
				// 比对state.userInfo是否发生变化，变化将isDataChanged置为True
				let result = JSON.stringify(state.userInfo) !== JSON.stringify(state.originUserInfo);
				state.isDataChanged = result
				console.log('watch state.isDataChanged', state.isDataChanged)
			}, {
				deep: true
			});

			watch(() => state.defaultSku, async (newValue, oldValue) => {
				console.log('watch state.defaultSku', state.defaultSku);
				if (state.defaultSku && state.defaultSku.sku) {
					const popup = vkDataGoodsSkuPopup.methods;
					await popup.defaultSelectSku(state.defaultSku);
				}
			});

			return {
				...toRefs(state),
				cityList,
				genderOption,
				gradeList,
				placeholderStyle,
				handleGenderChange,
				handleDateChange,
				handleCityChange,
				handleRelativeNameChange,
				handleRelativePhoneChange,
				openGradeTermPopup,
				onOpenGradeTermPopup,
				onCloseGradeTermPopup,
				confirmGradeTermSelection,
				savaInfo,
				delInfo,
				redirectScoreInput,
				redirectScoreInfo,
				url_input,
				url_info
			};
		}
	};
</script>

<style lang="scss" scoped>
	.user-info {
		.content {
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx;

			.info-item {
				display: flex;
				align-items: flex-start;
				flex-direction: column;
				padding-left: 40rpx;
				flex: 1;
				font-size: 70rpx;
				font-weight: 600;
				margin: 0rpx 50rpx;
			}
		}

		.line {
			margin: 10rpx;
			border-bottom: 1px solid #aaaaaa;
		}

		.tabContent {
			background: #fff;
			overflow: hidden;
		}

		.param-title {
			background: #f5f5f5;
			height: 80rpx;
			line-height: 80rpx;
			margin: 10rpx 30rpx 0;
			font-size: 28rpx;
			text-indent: 30rpx;
		}

		.param-item {
			height: 80rpx;
			line-height: 80rpx;
			font-size: 26rpx;
			border-bottom: 1rpx solid #f5f5f5;
			margin: 0 30rpx;
			border-left: 1rpx solid #f5f5f5;
			border-right: 1rpx solid #f5f5f5;
			padding: 0 30rpx;
			display: flex;
		}

		.param-item label {
			width: 260rpx;
			color: #999;
		}

		.button {
			width: 85%;
			font-size: 26rpx;
			font-weight: 550;
			border-style: hidden;
			margin-right: 60rpx;
		}

		.text {
			font-size: 28rpx;
			font-weight: 550;
		}

		.button-group {
			display: flex;
			width: 100%;
			justify-content: space-around;
			align-items: center;
		}

		.my-button {
			height: 80rpx;
			width: 300rpx;
			font-size: 28rpx;
			margin-bottom: 10rpx;
			font-weight: 600;
		}

		.picker {
			width: 100%;
			/* 设置宽度为整行宽度 */
			height: 80rpx;
			/* 可根据实际情况调整高度，保持和其他 param-item 一致 */
			line-height: 80rpx;
			font-size: 24rpx;
			display: flex;
			justify-content: flex-start;
			/* 将文本和展开图标两端对齐 */
			align-items: center;
			/* 垂直居中 */
			position: relative;
			/* 为了设置伪元素的定位 */
			padding-left: 110rpx;
		}

		.picker::after {
			content: "";
			position: absolute;
			right: 15rpx;
			/* 根据需要调整右侧距离，设置展开图标的位置 */
			top: 40%;
			width: 15rpx;
			height: 15rpx;
			border-top: 2rpx solid #999;
			border-right: 2rpx solid #999;
			transform: rotate(45deg);
		}

		.picker2 {
			width: 100%;
			/* 设置宽度为整行宽度 */
			height: 80rpx;
			/* 可根据实际情况调整高度，保持和其他 param-item 一致 */
			line-height: 80rpx;
			font-size: 24rpx;
			display: flex;
			justify-content: flex-start;
			/* 将文本和展开图标两端对齐 */
			align-items: center;
			/* 垂直居中 */
			position: relative;
			/* 为了设置伪元素的定位 */
			padding-left: 110rpx;
		}

		.input-border {
			border: #b3e5fc;
			border-radius: 5px;
			padding: 2px 4px;
		}

		.input-selected {
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			flex-direction: row;
			line-height: 2;
		}

		.data-pickerview {
			height: 300px;
			border: 1px solid #e5e5e5;
			border-radius: 5px;
			/* #ifndef APP-NVUE */
			overflow: hidden;
			/* #endif */
		}

		.data-changed-tip {
			background-color: #b3e5fc;
			color: red;
			font-size: 20rpx;
			margin: 10rpx;
			text-align: center;
		}
	}
</style>